//
//  ChooseWithBrandViewController.m
//  CarUser
//
//  Created by 王森林 on 2018/12/6.
//  Copyright © 2018年 王森林. All rights reserved.
//

#import "ChooseWithBrandViewController.h"
#import "ChooseHotBrandCell.h"
#import "ChooseHotCarCell.h"
#import "ChooseCommonCarCell.h"
#import "ChooseResultViewController.h"
@interface ChooseWithBrandViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) NSArray *hotBrandAry;
@property (nonatomic, strong) NSArray *hotCarAry;
@property (nonatomic, strong) NSMutableArray *totalCarAry;
@property (nonatomic, strong) NSArray *letterAry; //字母填充
@end

@implementation ChooseWithBrandViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self fetchDataFromNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataFromNet];
    }];
    // Do any additional setup after loading the view.
}

- (void)fetchDataFromNet
{
    //热门品牌
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"NULL"],
                             @"SFRX00":@"1"
                             
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_8 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
          [self.mainTableView.mj_header endRefreshing];
        NSDictionary *resultDict  = response;
        self.hotBrandAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
              [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    //热门车系
    NSDictionary *params1 = @{
                              @"FKEY":[CommonMethod createMD5Key:@"NULL"],
                              @"SFRX00":@"1"
                              
                              };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_9 params:params1 md5Paraname:nil success:^(id  _Nullable response) {
          [self.mainTableView.mj_header endRefreshing];
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        NSDictionary *resultDict  = response;
        self.hotCarAry  = [resultDict objectForKey:@"list"];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
        [self.mainTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
              [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    //获取品牌列表
    NSDictionary *params2 = @{
                              @"FKEY":[CommonMethod createMD5Key:@"NULL"]
                           
                              };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_8 params:params2 md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
          [self.mainTableView.mj_header endRefreshing];
        
        NSDictionary *resultDict  = response;
        [self packData:[resultDict objectForKey:@"list"]];
        [self.mainTableView reloadData];
//        self.totalCarAry  = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
//        [self.mainTableView reloadData];
//        NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:1];
//        [self.mainTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
              [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
    
    
    
    
}

// 组装数据
- (void)packData:(NSArray *)data
{
    NSMutableSet *set  = [[NSMutableSet alloc] init];
    [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = data[idx];
        [set addObject: [dict objectForKey:@"SZM000"]];
    }];
    
//    [set addObject:@"#"];
//    self.letterAry = [set allObjects];
    
//    NSComparator cmptr = ^(id obj1, id obj2){
//        if ([obj1 characterAtIndex:0] > [obj2 characterAtIndex:0]) {
//            return (NSComparisonResult)NSOrderedDescending;
//        }
//
//        if ([obj1 characterAtIndex:0] < [obj2 characterAtIndex:0]) {
//            return (NSComparisonResult)NSOrderedAscending;
//        }
//        return (NSComparisonResult)NSOrderedSame;
//    };
//
    self.letterAry =    [[set allObjects] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    
   self.totalCarAry = [NSMutableArray new];
    NSEnumerator *enumerator = [self.letterAry objectEnumerator];
    NSObject *object  = [enumerator nextObject];
    while (object != nil) {
        NSMutableArray *listAry = [NSMutableArray new];
        [data enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             NSDictionary *dict = data[idx];
            NSString *letter = [dict objectForKey:@"SZM000"];
            if ([letter isEqualToString:(NSString *)object]) {
                [listAry addObject:dict];
            }
        }];
        NSDictionary *resultDict = @{@"title":object,@"data":listAry};
        [self.totalCarAry addObject:resultDict];
        object = [enumerator nextObject];
    }
    
    
}


- (void)createUI
{
    self.mainTableView.frame  = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-NAV_HEIGHT-TABBAR_HEIGHT);
 
    [self.mainTableView setSectionIndexColor:RGB(127, 127, 127)];
    [self.mainTableView registerClass:[ChooseHotBrandCell class] forCellReuseIdentifier:@"ChooseHotBrandCell"];
    
    [self.mainTableView registerClass:[ChooseHotCarCell class] forCellReuseIdentifier:@"ChooseHotCarCell"];
    [self.mainTableView registerClass:[ChooseCommonCarCell class] forCellReuseIdentifier:@"ChooseCommonCarCell"];
    
}



#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 + self.totalCarAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
        {
            return 2;
        }
            break;
            
        default:
        {
            NSDictionary *secDict = self.totalCarAry[section-1];
            NSArray *ary = [secDict objectForKey:@"data"];
            return ary.count;
            
        }
            break;
    }
}
#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            if (indexPath.row  == 0) {
                  return 185.0f;
            } else {
                
                 return 155.0f;
            }
            
        }
            break;
            
        default:
        {
            return 60.0f;
        }
            break;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (section) {
        case 0:
        {
            return 0;
        }
            break;
            
        default:
        {
            return 20.0f;
        }
            break;
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDWIDTH, 20.0f)];
    headView.backgroundColor = Common_Head_Color;
    NSDictionary *secDict = self.totalCarAry[section-1];
    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, BOUNDWIDTH-15*2, 20.0f)];
    dateLabel.text =  [secDict objectForKey:@"title"];
    dateLabel.font = FONT_SIZE(12);
    dateLabel.textColor = Common_HeadTitle_Color;
    [headView addSubview:dateLabel];

    return headView;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            
            if (indexPath.row == 0) {
                
                ChooseHotBrandCell *cell = (ChooseHotBrandCell *)[tableView dequeueReusableCellWithIdentifier:@"ChooseHotBrandCell" forIndexPath:indexPath];
                cell.titleView.resultBlock = ^(id  _Nonnull response) {
                    NSIndexPath * dayOne = [NSIndexPath indexPathForRow:0 inSection:1];
                    [self.mainTableView scrollToRowAtIndexPath:dayOne atScrollPosition:UITableViewScrollPositionTop animated:YES];
                 
                };
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
               [cell setData:self.hotBrandAry];
                return cell;
                
            } else {
                ChooseHotCarCell *cell = (ChooseHotCarCell *)[tableView dequeueReusableCellWithIdentifier:@"ChooseHotCarCell" forIndexPath:indexPath];
                [cell setData:self.hotCarAry];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;

                return cell;
             
            }
          
        }
            break;
    
        default:
        {
            ChooseCommonCarCell *cell = (ChooseCommonCarCell *)[tableView dequeueReusableCellWithIdentifier:@"ChooseCommonCarCell" forIndexPath:indexPath];
        
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            NSDictionary *secDict = self.totalCarAry[indexPath.section-1];
            NSArray *dataAry = [secDict objectForKey:@"data"];
            NSDictionary *dataDict = dataAry[indexPath.row];
            [cell setImageWithName:[dataDict objectForKey:@"LOGO00"] withTitle:[dataDict objectForKey:@"PPMC00"]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }
            break;
    }
  
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    

    
    if (indexPath.section > 0) {
        
        NSDictionary *secDict = self.totalCarAry[indexPath.section-1];
        NSArray *ary = [secDict objectForKey:@"data"];

        NSDictionary *dict = ary[indexPath.row];
        ChooseResultViewController  *controller  = [[ChooseResultViewController alloc] init];
        controller.type = @"3";
        controller.pushType = 1;
        controller.SERIES_ID = [dict objectForKey:@"BRAND_ID"];
        [self.navigationController pushViewController:controller animated:YES];
    }
}


/**每一组的标题*/
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *secDict = self.totalCarAry[section-1];
    return [secDict objectForKey:@"title"];
}

/** 右侧索引列表*/
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
//    [self.set addObject:@"#"];
    return self.letterAry;
    
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
